package com.huan.rabbitmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.IntStream;

/**
 * 消息生产者
 *
 * @author huan.fu
 * @date 2018/11/5 - 14:10
 */
@Component
@Slf4j
public class RabbitProducer implements ApplicationListener<ContextRefreshedEvent> {
	/*
	 * 用于绑定正常发送消息的msgId和message,
	 * 以便RabbitConfirmCallback对发送成功的数据进行数据删除，没成功的重新发送或存数据库手动处理。
	 * 注意：msgId和message应该存入数据库持久化，这里演示就不这样处理了。数据库的这张表还需要增加一个计数字段，超过n次就手动处理
	 */
	public  static Map sendMap = new HashMap(); 
	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		String exchange = "exchange-rabbit-springboot-advance";
		String routingKey = "product";
		String unRoutingKey = "norProduct";

		// 1.发送一条正常的消息 CorrelationData唯一（可以在ConfirmListener中确认消息）
		IntStream.rangeClosed(0, 10).forEach(num -> {
			String msgId = "routing" + UUID.randomUUID().toString();
			String message = LocalDateTime.now().toString() + "发送第" + (num + 1) + "条消息.";
			sendMap.put(msgId, message);
			rabbitTemplate.convertAndSend(exchange, routingKey, message, new CorrelationData(msgId));
			log.info("发送一条消息,exchange:[{}],routingKey:[{}],message:[{}]", exchange, routingKey, message);
		});
		// 2.发送一条未被路由的消息，此消息将会进入备份交换器（alternate exchange）
		String message = LocalDateTime.now().toString() + "发送一条消息.";
		rabbitTemplate.convertAndSend(exchange, unRoutingKey, message, new CorrelationData("unRouting-" + UUID.randomUUID().toString()));
		log.info("发送一条消息,exchange:[{}],routingKey:[{}],message:[{}]", exchange, unRoutingKey, message);
	}
}